package z_whiteboard2;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.Button;
import java.awt.Rectangle;
import java.awt.List;
import java.util.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

public class ObjectMultiServer extends Frame implements ActionListener,Runnable{

	private static final long serialVersionUID = 1L;
	private Button startBtn = null;
	private Button stopBtn = null;
	public List userList = null;

	Vector v = new Vector();
	ServerSocket server = null;  //  @jve:decl-index=0:
	boolean threadFlag = true;

	private Button getStartBtn() {
		if (startBtn == null) {
			startBtn = new Button("서버시작");
			startBtn.setBounds(new Rectangle(75, 55, 90, 39));
			startBtn.addActionListener(this);
		}
		return startBtn;
	}

	private Button getStopBtn() {
		if (stopBtn == null) {
			stopBtn = new Button("서버 종료");
			stopBtn.setBounds(new Rectangle(173, 55, 96, 40));
			stopBtn.addActionListener(this);
		}
		return stopBtn;
	}

	private List getUserList() {
		if (userList == null) {
			userList = new List();
			userList.setBounds(new Rectangle(48, 108, 243, 157));
		}
		return userList;
	}

	public static void main(String[] args) {
		ObjectMultiServer oms = new ObjectMultiServer();
	}

	/**
	 * This is the default constructor
	 */
	public ObjectMultiServer() {
		super();
		initialize();
		this.setVisible(true);
	}

	private void initialize() {
		this.setLayout(null);
		this.setSize(339, 293);
		this.setTitle("Object 다중 채팅 서버");

		this.add(getStartBtn(), null);
		this.add(getStopBtn(), null);
		this.add(getUserList(), null);
		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(java.awt.event.WindowEvent e) {
				System.exit(0);
			}
		});
	}

	public void run(){
		try{
			while( threadFlag ){

				Socket s = server.accept();
				ObjectClient oc = new ObjectClient(this, s);
				v.add(oc);
				System.out.println("ok");
			}

			// 서버 종료에 대한 사전 처리
			System.out.println("stop");
			VData d = new VData();
			d.command = "shutdown";
			d.msg = "서버가 중지됩니다.";
			userList.validate();

			for(int i=0 ; i< v.size() ; i++){
				ObjectClient oc = (ObjectClient)v.get(i);
				oc.send.writeObject(d);
				oc.send.flush();
				oc.threadFlag = false;
			}

			v.removeAllElements();

		}catch(Exception ex){
			userList.add(ex.toString());
		}

	}


	public void actionPerformed(ActionEvent e){
		if( e.getSource() == startBtn){
			try{
				server = new ServerSocket(11111);
				new Thread(this).start();
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}

		if(e.getSource() == stopBtn){
			threadFlag = false;
		}
	}










}  //  @jve:decl-index=0:visual-constraint="10,10"
